import { useUser } from '@/stores/user';

// 设置token
export function setToken(token: string) {
  const userStore = useUser();
  try {
    uni.setStorageSync('token', token);
    userStore.setLoginStatus(true);
  } catch (e) {
    console.log('set token error', e);
  }
}

// 获取token
export function getLocalToken() {
  try {
    return uni.getStorageSync('token');
  } catch (e) {
    console.log('get token error', e);
  }
  return '';
}

// 设置订阅日期
export function setSubscribeDay() {
  try {
    // 将当前日期存入本地
    uni.setStorageSync('subscribeDay', new Date().getDate());
  } catch (e) {
    console.log('set subscribeDay error', e);
  }
}

// 获取订阅日期
export function getSubscribeDay() {
  try {
    return uni.getStorageSync('subscribeDay');
  } catch (e) {
    console.log('get subscribeDay error', e);
  }
}

/** 设置520弹窗日期 */
export const set520PopupDay = () => {
  try {
    uni.setStorageSync('520PopupDay', new Date().getDate());
  } catch (e) {
    console.log('set 520PopupDay error', e);
  }
};

/** 获取520弹窗日期 */
export const get520PopupDay = () => {
  try {
    return uni.getStorageSync('520PopupDay');
  } catch (e) {
    console.log('get 520PopupDay error', e);
  }
};

/** 删除testInfo数据 */
export const removeTestInfo = () => {
  uni.removeStorageSync('testInfo');
};

/**
 * 添加新的testInfo条目
 * @param method 请求的方法，可选
 * @param apiUrl 请求的api地址
 * @param data 请求的参数，可选
 * @param options 请求的其他参数，可选
 * @param res 请求的返回值，可选
 */
export const addNewTestInfo = (
  apiUrl: string,
  res: any = {},
  method: 'post' | 'put' | 'delete' | 'get' = 'get',
  data: AnyObject = {},
  options: AnyObject = {},
) => {
  const oldTestInfo = JSON.parse(uni.getStorageSync('testInfo') || '{}');
  const time = new Date().getTime().toString();
  const newTestInfo = {
    [time]: {
      apiUrl,
      method,
      data,
      options,
      res,
    },
    ...oldTestInfo,
  };

  uni.setStorageSync('testInfo', JSON.stringify(newTestInfo));
};
